package com.hzit.irs.controller;

import com.google.code.kaptcha.Producer;
import com.hzit.irs.resp.MenuData;
import com.hzit.irs.resp.RespVo;
import com.hzit.irs.service.IAdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

/**
 * 系统用户管理
 */
@Controller
public class AdminController {

    @Autowired
    private IAdminService adminService;

    @Autowired
    private Producer captchaProducer = null;

    private Logger logger = LoggerFactory.getLogger(AdminController.class);


    /**
     * 加载登录页面
     *
     */
    @RequestMapping("/show")
    public String show(){
        return "redirect:/login.html";
    }

    /**
     * 登录 shiro
     * @param username
     * @param password
     * @param vcode
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sys/login")
//    @PostMapping
    public RespVo<String> login(HttpServletRequest request,
                                @RequestParam("username") String username,
                                @RequestParam("password") String password,
                                @RequestParam("vcode") String vcode){

        logger.info("######接收到前端的登录请求，请求参数：username:{}," +
                "password:{},vcode:{}############",username,password,vcode);

        if (StringUtils.isEmpty(username)){
            return RespVo.returnFail("用户名不能为空");
        }
                          //盐
        //123456abcd667 + "abcd667"
        if (StringUtils.isEmpty(password)){
            return RespVo.returnFail("密码不能为空");
        }
        if (StringUtils.isEmpty(vcode)){
            return RespVo.returnFail("验证码不能为空");
        }

        HttpSession session = request.getSession();
        String sessionVcode = (String)session.getAttribute("vCode");
        logger.info("缓存中的验证码：{}",sessionVcode);

        if (!vcode.equals(sessionVcode)){
            return RespVo.returnFail("验证码输入不正确");
        }
        //shiro来认证
        Subject subject = SecurityUtils.getSubject(); // 获取当前主体
        String md5PassWord = new Md5Hash(password).toString();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,md5PassWord);
        subject.login(usernamePasswordToken);

        logger.info(" isLogin :{}",subject.isAuthenticated());


        return RespVo.succes("登录成功");

    }


    @ResponseBody
    @RequestMapping("/sys/vcode")
    public void createVcode(HttpServletRequest request, HttpServletResponse response){
        logger.info("#########接收到生成验证码的请求########");

        //放验证码
        HttpSession httpSession = request.getSession();

        //生成验证码
        String vCode = captchaProducer.createText();

        httpSession.setAttribute("vCode",vCode);

        //返回验证码
        BufferedImage bufferedImage = captchaProducer.createImage(vCode);

        try {
            ImageIO.write(bufferedImage,"JPEG",response.getOutputStream());
        } catch (IOException e) {
            logger.error("IOException",e);
        }
    }


    /**
     * 加载首页
     * @return
     */
    @RequestMapping("/sys/index")
    public String index(){
        return "redirect:/index.html";
    }



    /**
     * 获取菜单
     * @return
     */
    @ResponseBody
    @RequestMapping("/sys/getMenus")
    public RespVo<List<MenuData>> getMenus(){

        RespVo<List<MenuData>> respVo = new RespVo<List<MenuData>>();

        List<MenuData> menuDataList = adminService.queryMenus();

        respVo.setCode(0);
        respVo.setMsg("ok");
        respVo.setData(menuDataList);
        return respVo;
    }
}
